package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author majun
 * @package sky-take-out
 * @date 2024/5/31 : 上午8:19
 */

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    public List<AddressBook> list() {

        Long userId = BaseContext.getCurrentId();

        List<AddressBook> list = addressBookMapper.list(userId);

        return list;

    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    public void add(AddressBook addressBook) {

        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(StatusConstant.DISABLE);

        addressBookMapper.add(addressBook);

    }

    /**
     * 查询默认地址
     *
     * @return
     */
    public AddressBook def() {

        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();

        addressBook.setUserId(userId);
        addressBook.setIsDefault(StatusConstant.ENABLE);

        AddressBook list = addressBookMapper.def(addressBook);

        return list;
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    public AddressBook getFromById(Long id) {

        AddressBook list = addressBookMapper.getFromById(id);

        return list;

    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void put(AddressBook addressBook) {

        addressBookMapper.put(addressBook);

    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void delete(Long id) {

        addressBookMapper.detele(id);

    }

    /**
     * 修改默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void putDef(AddressBook addressBook) {

        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(StatusConstant.ENABLE);

        //查询用户默认地址
        AddressBook def = addressBookMapper.def(addressBook);

        if (def == null) {

            //默认地址为空，用户未设置默认地址
            addressBookMapper.put(addressBook);

        } else {

            //有默认地址，先修改默认地址，后取消原先默认地址

            addressBookMapper.put(addressBook);

            Long id = def.getId();

            addressBook.setId(id);
            addressBook.setIsDefault(StatusConstant.DISABLE);

            addressBookMapper.put(addressBook);

        }

    }

}
